<!-- 用户管理 -->
<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!-- 用户列表 -->
      <el-col :lg="24" :xs="24">
        <!-- 搜索区域 -->
        <div class="search-container">
          <el-form
            ref="queryFormRef"
            :model="queryParams"
            :inline="true"
            label-width="auto"
          >
            <el-form-item label="权限组" prop="group_id">
              <el-select
                v-model="queryParams.group_id"
                placeholder="全部"
                clearable
                style="width: 100px"
              >
                <el-option label="全部" value="" />
                <el-option
                  v-for="item in groupOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id ?? ''"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="关键字" prop="keywords">
              <el-input
                v-model="queryParams.keywords"
                placeholder="用户名/真实姓名"
                clearable
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="全部"
                clearable
                style="width: 100px"
              >
                <el-option label="正常" :value="1" />
                <el-option label="禁用" :value="2" />
              </el-select>
            </el-form-item>

            <el-form-item label="创建时间">
              <el-date-picker
                v-model="queryParams.createTime"
                :editable="false"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="截止时间"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item class="search-buttons">
              <el-button type="primary" icon="search" @click="handleQuery">
                搜索
              </el-button>
              <el-button icon="refresh" @click="handleResetQuery">
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="hover" class="data-table">
          <div class="data-table__toolbar" style="margin-bottom: 10px">
            <div class="data-table__toolbar--actions">
              <el-button
                v-hasPerm="['authUserEdit']"
                type="success"
                icon="plus"
                @click="handleOpenDialog()"
              >
                新增
              </el-button>
              <el-button
                v-hasPerm="'authUserDelBtn'"
                type="danger"
                icon="delete"
                :disabled="selectIds.length === 0"
                @click="handleDelete()"
              >
                删除
              </el-button>
            </div>
            <div class="data-table__toolbar--tools">
              <el-button
                v-hasPerm="'sys:user:import'"
                icon="upload"
                @click="handleOpenImportDialog"
              >
                导入
              </el-button>

              <el-button
                v-hasPerm="'sys:user:export'"
                icon="download"
                @click="handleExport"
              >
                导出
              </el-button>
            </div>
          </div>

          <el-table
            v-loading="loading"
            :data="pageData"
            :selectable="selectable"
            border
            stripe
            highlight-current-row
            class="data-table__content"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户名" prop="username" />
            <el-table-column label="头像" align="center" width="100">
              <template #default="scope">
                <el-avatar :size="50" :src="scope.row.avatar" />
              </template>
            </el-table-column>
            <el-table-column label="真实姓名" align="center" prop="realname" />
            <el-table-column
              label="权限组"
              width="200"
              align="center"
              prop="group_name"
            />
            <el-table-column
              label="状态"
              align="center"
              prop="status"
              width="100"
            >
              <template #default="scope">
                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                  {{ scope.row.status == 1 ? "正常" : "禁用" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="登录次数"
              align="center"
              prop="login_num"
              width="120"
            />
            <el-table-column
              label="最后登录IP"
              align="center"
              prop="login_last_ip"
              width="200"
            />
            <el-table-column
              label="最后登录时间"
              align="center"
              prop="login_last_at"
              width="200"
            />
            <el-table-column
              label="创建时间"
              align="center"
              prop="created_at"
              width="200"
            />
            <el-table-column
              label="更新时间"
              align="center"
              prop="updated_at"
              width="200"
            />
            <el-table-column label="操作" fixed="right" align="center">
              <template #default="scope">
                <el-button
                  v-hasPerm="'authUserEdit'"
                  type="primary"
                  icon="edit"
                  link
                  size="small"
                  @click="handleOpenDialog(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-hasPerm="'authUserDelBtn'"
                  type="danger"
                  icon="delete"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="queryParams.page"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[15, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleQuery"
            @current-change="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000"
      :before-close="handleCloseDialog"
      :align-center="true"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            :readonly="!!formData.id"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="formData.password" placeholder="请输入登录密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="formData.realname" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <SingleImageUpload v-model="formData.avatar" />
        </el-form-item>
        <el-form-item label="角色" prop="group_id">
          <el-select v-model="formData.group_id" placeholder="请选择">
            <el-option
              v-for="item in groupOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id ?? ''"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            inline-prompt
            active-text="正常"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入 -->
    <UserImport v-model="importDialogVisible" @import-success="handleQuery()" />
  </div>
</template>

<script setup lang="ts">
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import { useAppStore } from "@/store/modules/app";
import { DeviceEnum } from "@/enums/DeviceEnum";

import GroupAPI, { GroupListVO, GroupList } from "@/api/system/group.api";
import UserAPI, {
  UserForm,
  UserListVO,
  UserPageQuery,
  UserList,
} from "@/api/system/user.api";

import UserImport from "./components/UserImport.vue";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const userFormRef = ref();

const queryParams = reactive<UserPageQuery>({
  page: 1,
  pageSize: 15,
});
const selectable = (row: UserForm) => ![1].includes(Number(row.id));
const pageData = ref<UserList[]>();
const total = ref(0);
const loading = ref(false);

const dialog = reactive({
  visible: false,
  title: "新增用户",
});
const drawerSize = computed(() =>
  appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"
);

let formData = reactive<UserForm>({
  id: "",
  username: "",
  password: "",
  realname: "",
  avatar: "",
  group_id: "",
  status: 1,
});

const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  realname: [{ required: true, message: "真实姓名不能为空", trigger: "blur" }],
  group_id: [{ required: true, message: "所属角色不能为空", trigger: "blur" }],
});

// 选中的用户ID
const selectIds = ref<number[]>([]);
// 角色下拉数据源
const groupOptions = ref<GroupList[]>();
// 导入弹窗显示状态
const importDialogVisible = ref(false);

// 查询
async function handleQuery() {
  loading.value = true;
  UserAPI.getPage(queryParams)
    .then((data: UserListVO) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 初始化查询参数
async function initParams() {
  GroupAPI.getPage({ page: 1, pageSize: 1000 })
    .then((data: GroupListVO) => {
      groupOptions.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page = 1;
  queryParams.group_id = "";
  queryParams.status = "";
  queryParams.keywords = "";
  queryParams.createTime = undefined;
  handleQuery();
}

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
async function handleOpenDialog(user?: UserForm) {
  dialog.visible = true;
  if (user?.id) {
    dialog.title = "修改用户";
    //复制 user 给formData.value
    Object.assign(formData, user);
  } else {
    dialog.title = "新增用户";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = "";
  formData.username = "";
  formData.password = "";
  formData.group_id = "";
  formData.realname = "";
  formData.status = 1;
}

// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  userFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        UserAPI.update(formData)
          .then(() => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        UserAPI.create(formData)
          .then(() => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

/**
 * 删除用户
 *
 * @param id  用户ID
 */
function handleDelete(id?: number) {
  const userIds = [id || selectIds.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      console.log(userIds);
      UserAPI.deleteByIds({ ids: userIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开导入弹窗
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

// 导出用户
function handleExport() {
  // UserAPI.export(queryParams).then((response: any) => {
  //   const fileData = response.data;
  //   const fileName = decodeURI(
  //     response.headers["content-disposition"].split(";")[1].split("=")[1]
  //   );
  //   const fileType =
  //     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

  //   const blob = new Blob([fileData], { type: fileType });
  //   const downloadUrl = window.URL.createObjectURL(blob);

  //   const downloadLink = document.createElement("a");
  //   downloadLink.href = downloadUrl;
  //   downloadLink.download = fileName;

  //   document.body.appendChild(downloadLink);
  //   downloadLink.click();

  //   document.body.removeChild(downloadLink);
  //   window.URL.revokeObjectURL(downloadUrl);
  // });
}

onMounted(() => {
  initParams();
  handleQuery();
});
</script>
